Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

328
Vistas
React Hook "useEffect" is called conditionally

React is complaining about code below, saying it useEffect is being called conditionally:

import React, { useEffect, useState } from 'react'
import VerifiedUserOutlined from '@material-ui/icons/VerifiedUserOutlined'
import withStyles from '@material-ui/core/styles/withStyles'
import firebase from '../firebase'
import { withRouter } from 'react-router-dom'

function Dashboard(props) {
  const { classes } = props
  
  const [quote, setQuote] = useState('')

    if(!firebase.getCurrentUsername()) {
        // not logged in
        alert('Please login first')
        props.history.replace('/login')
        return null
    }

    useEffect(() => {
        firebase.getCurrentUserQuote().then(setQuote)
    })

    return (
        <main>
            // some code here
        </main>
    )

    async function logout() {
        await firebase.logout()
        props.history.push('/')
    }
}

export default withRouter(withStyles(styles)(Dashboard))

And that returns me the error:

React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render.

Does anyone happen to know what the problem here is?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Your code, after an if statement that contains return, is equivalent to an else branch:

if(!firebase.getCurrentUsername()) {
    ...
    return null
} else {
    useEffect(...)
    ...
}

Which means that it's executed conditionally (only when the return is NOT executed).

To fix:

useEffect(() => {
  if(firebase.getCurrentUsername()) {
    firebase.getCurrentUserQuote().then(setQuote)
  }
}, [firebase.getCurrentUsername(), firebase.getCurrentUserQuote()])

if(!firebase.getCurrentUsername()) {
  ...
  return null
}
over 4 years ago · Santiago Trujillo Denunciar

0

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. You can follow the documentation here.

I couldn't find the use case in the above code. If you need the effect to run when the return value of firebase.getCurrentUsername() changes, you might want to use it outside the if condition like:

useEffect(() => {
    firebase.getCurrentUserQuote().then(setQuote)
}, [firebase.getCurrentUsername()]);
over 4 years ago · Santiago Trujillo Denunciar

0

I had a similar problem with the same error message, where the order of variable declarations was the source of the error:

Bad example

if (loading) return <>loading...</>;
if (error) return <>Error! {error.message}</>;

const [reload, setReload] = useState(false);

Good example

const [reload, setReload] = useState(false);

if (loading) return <>loading...</>;
if (error) return <>Error! {error.message}</>;

The hook needs to be created before potential conditional return blocks

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda